<?php

namespace app\backmanage\controller;

use app\common\exceptions\ErrException;
use app\common\model\common\MemberVipOrders as Model;
use app\common\model\common\SpreadUsers;
use thans\layuiAdmin\facade\AdminsAuth;
use thans\layuiAdmin\facade\Json;
use thans\layuiAdmin\Traits\FormActions;
use think\Request;
use think\facade\View;

class MemberVipOrder extends Base
{
    use FormActions;

    protected $route_alias = 'member_vip_order';
    protected $title = '会员卡订单管理';
    protected $vip_key = 'crm:user_vip_renew:member_id-%dtype-%d';

    protected $cols = [
        ['field' => 'id', 'title' => 'ID', 'sort' => true, 'width' => 100],
		['field' => 'partition_id', 'title' => '分区号', 'width' => 80],
        ['field' => 'partition_name', 'title' => '分区名称', 'width' => 100],
        ['field' => 'nickname', 'title' => '主播昵称', 'width' => 150],
        ['field' => 'mobile', 'title' => '主播手机号', 'width' => 150],
        ['field' => 'member_id', 'title' => '主播ID', 'width' => 100],
        ['field' => 'vip_order_sn', 'title' => '订单号', 'width' => 260],
        ['field' => 'vip_class_id', 'title' => '卡类型', 'type' => "button", 'option' => [[1, '月卡', 'warm'], [2, '年卡', 'normal'], [3, '体验版'],[5, '专享年卡','danger'],[6, '月卡', 'warm'],[7, '季卡'], [8, '年卡', 'normal'],[9, '日卡', '']], 'width' => 100],
        ['field' => 'vip_price', 'title' => '充值金额', 'width' => 100],
        ['field' => 'pay_type', 'title' => '支付方式', 'type' => "button", 'option' => [[1, '微信支付'], [2, '支付宝支付'], [3, '苹果内购'], [4, '线下充值'],[5, '权益转让']], 'width' => 120],
        ['field' => 'pay_status', 'title' => '支付状态', 'type' => "button", 'option' => [[1, '未支付'], [2, '已支付', 'normal'], [3, '取消支付'], [30, '已退款', 'danger'], [40, '已接收', 'normal'], [50, '已转让', 'danger']], 'width' => 120],
        ['field' => 'is_first_open_card', 'title' => '首次为首次开卡', 'type' => "button", 'option' => [[ 0, '未开卡/赠送卡'], [1, '首次开卡','normal'], [2, '续卡开卡','warm']], 'width' => 150],
        ['field' => 'pay_time', 'title' => '支付时间', 'type' => "time", 'width' => 200],
        ['field' => 'vip_end_timed', 'title' => 'VIP到期时间', 'width' => 200],
        ['field' => 'create_time', 'title' => '创建时间', 'width' => 200],
		['field' => 'pid', 'title' => '销售ID', 'sort' => true,'width' => 100],
		['field' => 'realname', 'title' => '销售姓名', 'sort' => true,'width' => 100],
		['field' => 'refund_market', 'title' => '退款备注', 'width' => 200],
        ['field' => 'right', 'title' => '操作', 'toolbar' => '#barDemo', 'width' => 200, 'fixed' => 'right'],
    ];

    public function index(Request $request)
    {
        if ($request->isAjax() || $request->isPost()) {
            list($where, $order, $page, $limit) = self::buildParams('id|member_id|vip_order_sn|vip_class_id|vip_price|pay_type|pay_status|pay_time|transaction_id|create_time|pid');
			$partitionId='';
            foreach ($where as $key => $value) {
				 if ($value[0] == 'partition_id') {
                    unset($where[$key]);
                    $partitionId=$value[2];
                }
            }
            if ($partitionId===""){
                return Json::success('获取成功', [], ['total' => 0,'count' => 0]);
            }
            
            // 使用封装的方法调用分区API
            $ret = $this->callPartitionApi($partitionId, '/backmanage/VipRenew/index');
            
            if ($ret['code'] != 0) {
                return json($ret);
            }
            
            return Json::success('获取成功', $ret['data'], [
                'total' => $ret['total'], 
                'count' => $ret['total'],
                'actuallyPaidAmount' => $ret['actuallyPaidAmount'],
                'actualCollectionAmount' => $ret['actualCollectionAmount']
            ]);
        } else {
            //获取销售人员列表
            $spreads=\app\common\model\common\SpreadUser::where([
                'status'=>1
            ])->column('realname','member_id');
            //整理成数组
            $lists[0]='无';
            if ($spreads){
                foreach ($spreads as $memberId=>$realname){
                    $lists[$memberId]=$realname;
                }
            }
            // 使用封装的方法获取分区包信息
            list($partitionId,$partitions) = $this->getPartitionPackageInfo();
            $data = [];
            $data['cols'] = $this->cols;
            $data['title'] = $this->title;
            $data['search'][] = ['type' => 'select', 'field' => 'partition_id', 'desc' => '分区号', 'option' => $partitions,'default'=>$partitionId];
            $data['search'][] = ['type' => 'text', 'field' => 'mobile', 'desc' => '手机号'];
			$data['search'][] = ['type' => 'text', 'field' => 'vip_order_sn', 'desc' => 'VIP订单号'];
            $data['search'][] = ['type' => 'select', 'field' => 'vip_class_id', 'desc' => 'VIP充值类型', 'option' => [1 => '月卡',7 => '季卡', 2 => '年卡', 9=>'日卡',3 => '体验版',5 => '专享年卡']];
            $data['search'][] = ['type' => 'select', 'field' => 'pay_status', 'desc' => '支付状态', 'option' => [1 => '未支付', 2 => '已支付', 3 => '取消支付', 30 => '已退款',40=>'已接收',50=>'已转让']];
            $data['search'][] = ['type' => 'select', 'field' => 'pay_type', 'desc' => '支付方式', 'option' => [1 => '微信支付', 2 => '支付宝支付', 3 => '苹果支付', 4 => '线下支付',5=>'权益转让']];
            $data['search'][] = ['type' => 'time', 'field' => 'pay_time', 'desc' => '支付时间'];
            $data['search'][] = ['type' => 'text', 'field' => 'keyword', 'desc' => '关键字搜索'];
            $data['search'][] = ['type' => 'time', 'field' => 'create_time', 'desc' => '创建日期'];
			$data['search'][] = ['type' => 'select', 'field' => 'pid', 'desc' => '销售人员','option' =>$lists];
			$data['search'][] = ['type' => 'select', 'field' => 'trial_version_filterate', 'desc' => '体验版过滤', 'option' => [1 => '不过滤', 2 => '过滤']];
			$data['search'][] = ['type' => 'select', 'field' => 'test_filterate', 'desc' => '测试号过滤', 'option' => [1 => '不过滤', 2 => '过滤']];

            $data['list_url'] = '/backmanage/' . $this->route_alias . '/index';
            $create_url = '/backmanage/' . $this->route_alias . '/create';
            $data['go_back_url'] = '/backmanage/' . $this->route_alias . '/go_back';
			$data['bind_url'] = '/backmanage/' . $this->route_alias . '/bindUser';
            if (AdminsAuth::check($create_url)) {
                $data['create_url'] = $create_url;
            }
			$data['partition_id']=$partitionId;
            return View::fetch('member_vip_order/index', $data);
        }
    }

    public function go_back(Request $request)
    {
		if (empty($request->param('id'))) ErrException::throwExcep(-100, 'id不能为空');
		$partitionId=$request->param('partition_id','');
		if ($partitionId==="") {
            return json(['code' => -100, 'msg' => '分区号不能为空']);
        }
        $market = $request->param('transaction_id','');
        $market = trim($market);
        if(!$market){
            return json(['code' => -1, 'msg' => '请输入内容！']);
        }
        if(mb_strlen($market)<10 || mb_strlen($market)>200){
            return json(['code' => -1, 'msg' => '备注请输入10-200字！']);
        }
		// 使用封装的方法调用分区API
		$ret = $this->callPartitionApi($partitionId, '/backmanage/VipRenew/index');
		if ($ret['code'] != 0) {
			return json($ret);
		}
		return json(['code' => 0, 'msg' => '操作成功', 'data' => '']);
    }

    public function create(Request $request)
    {
        if ($request->isPost()) {
            $param = $request->all();
			if(empty($param['mobile'])){
				 return json(['code' => -100, 'msg' => '主播手机号不能为空']);
			}
			//获取手机号所在分区
			$partitionId=(new \app\common\model\common\AnchorMigration())->where([
				'mobile'=>$param['mobile'],
				'status'=>1
			])->value('partition_id')?:'';
			if ($partitionId==="") {
				return json(['code' => -100, 'msg' => '该主播手机号无效']);
			}
            // 使用封装的方法调用分区API
			$ret = $this->callPartitionApi($partitionId, '/backmanage/VipRenew/create');
			if ($ret['code'] != 0) {
				return json($ret);
			}
            return json(['code' => 0, 'msg' => '修改成功', 'data' => '']);
        } else {
			$spreads=\app\common\model\common\SpreadUser::where([
                'status'=>1
            ])->column('realname','member_id');
            //整理成数组
            $lists[0]='无';
            if ($spreads){
                foreach ($spreads as $memberId=>$realname){
                    $lists[$memberId]=$realname;
                }
            }
			$cards=[
				[2, '年卡', ''],[1, '月卡'],[7, '季卡', ''],[9,'日卡','']
			];
            $data['cols'] = [
                ['field' => 'vip_class_id', 'title' => 'VIP充值类型', 'type' => "button", 'option' =>$cards ],
				['field' => 'pay_order_num', 'title' => '试用天数','desc'=>'日卡天数 仅支持整数', 'style' => 'display: none;','aux_desc' => '仅支持日卡使用'],
                ['field' => 'mobile', 'title' => '手机号'],
                ['field' => 'pid', 'title' => '销售人员ID绑定' ,'type' => "button",'option' =>$lists],
                ['field' => 'transaction_id', 'title' => '第三方订单号'],
                ['field' => 'vip_end_time', 'title' => '预计到期时间', 'readonly' => true],
                ['field' => 'pay_type',   'title' => '支付方式', 'type' => "button", 'option' => [[4, '线下充值']]],
                ['field' => 'pay_status', 'title' => '支付状态', 'type' => "button", 'option' => [[2, '已支付'], [1, '未支付']]],
            ];
            $data['title'] = $this->title;

            return View::fetch('member_vip_order/add', $data);
        }
    }
    
    //绑定用户页面
    public function bindUser(Request $request){
    	$id=request()->param('id',0);
        if(!$id){
             return json(['code' => -100, 'msg' => 'ID不能为空']);
        }
    	$partitionId=$request->param('partition_id','');
		if ($partitionId==="") {
            return json(['code' => -100, 'msg' => '分区号不能为空']);
        }
        $subMemberModel=$this->getPartitionDatabase($partitionId);
        //查询订单信息
        $order=$subMemberModel->table('member_vip_orders')->where([
            'id'=>$id,
            'pid'=>0
        ])->find();
        if(empty($order['id'])){
             return json(['code' => -100, 'msg' => 'ID无效']);
        }
        //获取用户数据
        $member=$subMemberModel->table('member')->where([
            'id'=>$order['member_id']
        ])->field(['id','nickname','vip_end_time','mobile'])->find();
        $order['mobile']=$member['mobile']??'';
        $order['nickname']=$member['nickname']??'';
        $order['vip_end_time']=$member['vip_end_time']??'';
        $spreads=\app\common\model\common\SpreadUser::where([
            'status'=>1
        ])->column('realname','member_id');
		return View::fetch('member_vip_order/bind_user', [
			'order'=>$order??[],
			'spreads'=>$spreads??[]
		]);
	}
	
	//绑定销售操作
	public function toBindUser(){
    	$id=request()->param('id');
    	$pid=request()->param('pid');
    	if (!$pid){
			ErrException::throwExcep(-100, '销售不能为空');
		}
    	
	}
	
}
